<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeesSimple } from '@/api/employees'
import { addDepartment, getDepartmentById, updateDepartment } from '@/api/department'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义校验规则
    const validCode = (rule, value, callback) => {
      let existCode = this.originList.map(item => item.code)
      console.log(existCode)
      // 若果是编辑的状态,需要把当前的部门的编码从已经存在的数组中移出
      if (this.isEdit) {
        existCode = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (existCode.includes(value)) {
        callback(new Error(`你输入的部门编码:${value}已存在,请重新输入`))
      } else {
        callback()
      }
    }

    // 校验同级下部门名称不能重复
    const validName = (rule, value, callback) => {
      // 筛选出已有的部门名称
      let existName = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      if (this.isEdit) {
        // 拿到当前部门的pid
        const pid = this.originList.find(item => item.id === this.id).pid
        // 过滤出除了自身之外的兄弟 this.originList.filter(item => item.pid === pid)
        existName = this.originList.filter(item => item.pid === pid).filter(item => item.id !== this.id).map(item => item.name)
      }
      console.log('existName', existName)
      if (existName.includes(value)) {
        callback(new Error('你输入的部门名称已存在,请重新输入'))
      } else {
        callback
      }
    }

    return {
      list: [],
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 15, message: '请输入1-15位的名称', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入编码', trigger: 'blur' },
          { min: 1, max: 15, message: '请输入1-15位的编码', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入负责人名称', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1-300字的部门介绍', trigger: 'blur' }
        ]
      }
    }
  },
  // 解决公用组件数据不更新的方式3 watch
  watch: {
    // 可以监听props中的属性 和 data中的属性
    // id: function(newVal, oldVal) {
    //   console.log('newVal', newVal)
    //   console.log('oldVal', oldVal)
    //   if (this.isEdit) {
    //     this.loadDepartmentById()
    //   }
    // }
    // id: {
    //   // 如果用箭头函数 则this的指向会有问题 不要在watch中使用箭头函数
    //   handler: function(newVal, oldVal) {
    //     console.log('newVal', newVal)
    //     console.log('oldVal', oldVal)
    //     this.loadDepartmentById()
    //   }
    // }
  },
  created() {
    this.loadEmployeesSimple()
    if (this.isEdit) {
      this.loadDepartmentById()
    }
  },
  methods: {
    reSet() {
      this.$refs.deptForm.resetFields()
    },
    // 根据id获取部门详情
    async loadDepartmentById() {
      const res = await getDepartmentById(this.id)
      console.log(res)
      this.form = res.data
      // if (res.code !== 10000) return this.$message.error(res.message)
      // this.$message.success(res.message)
    },
    // 获取员工简单列表
    async loadEmployeesSimple() {
      try {
        const res = await getEmployeesSimple()
        console.log(res.data)
        // 将获取的员工信息保存到list中
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 新增部门
    async doAdd() {
      try {
        const res = await addDepartment({ pid: this.id, ...this.form })
        console.log('doAdd', res)
        // this.loadEmployeesSimple()
        // 子传父
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 修改部门
    async doEdit() {
      const res = await updateDepartment(this.form)
      console.log(res)
      this.$emit('success')
    },
    hSubmit() {
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
      })
      this.isEdit ? this.doEdit() : this.doAdd()
    },
    hCancel() {
      this.$emit('close')
    }

  }
}
</script>

<style>

</style>
